package com.miniapp.controller;

import com.github.vioao.wechat.api.component.wxa.CodeApi;
import com.github.vioao.wechat.api.component.wxa.MemberApi;
import com.github.vioao.wechat.bean.response.BaseResponse;
import com.miniapp.conifg.wechatOpen.WechatDomainProperties;
import com.miniapp.dto.MiniAppSimpleDTO;
import com.miniapp.entity.MiniProductEntity;
import com.miniapp.entity.MiniTesterEntity;
import com.miniapp.entity.MiniUserProductEntity;
import com.miniapp.entity.MiniVersionLogEntity;
import com.miniapp.entity.enums.MiniVersionStatus;
import com.miniapp.exception.RRException;
import com.miniapp.service.*;
import com.miniapp.service.impl.WxOpenService;
import com.miniapp.utils.BaseUtils;
import com.miniapp.utils.R;
import io.swagger.annotations.Api;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import weixin.popular.api.WxaAPI;
import weixin.popular.bean.wxa.GetQrcodeResult;
import weixin.popular.bean.wxa.Getwxacode;
import weixin.popular.bean.wxa.LineColor;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Api
@RestController()
@RequestMapping("/version")
public class MiniVersionController extends AbstractController {
    @Autowired
    protected WxOpenService wxOpenService;
    @Resource
    private MiniUserProductService miniUserProductService;
    @Autowired
    private MiniTesterService miniTesterService;
    @Autowired
    private MiniVersionLogService miniVersionLogService;
    @Autowired
    private MiniProductService miniProductService;
    @Autowired
    protected WechatDomainProperties wechatDomainProperties;
    /**
     * 获取版本信息
     */
    @GetMapping("/get_main")
    @ResponseBody
    public R getVersionInfo(){
        //1.版本信息
        MiniUserProductEntity miniUserProduct = miniUserProductService.findByAppid(getAppid());
        List<MiniAppSimpleDTO> info = new ArrayList<>();
        List<MiniVersionLogEntity> miniVersionLogs = miniVersionLogService.findByUserProductId(miniUserProduct.getId());
        MiniProductEntity miniProduct = miniProductService.getById(miniUserProduct.getProductId());
        MiniAppSimpleDTO dto1 = new MiniAppSimpleDTO();
        dto1.setData("线上版本：");
        dto1.setText("暂无线上版本");
        MiniAppSimpleDTO dto2 = new MiniAppSimpleDTO();
        dto2.setData("审核版本：");
        dto2.setText("暂无审核版本");
        if (miniVersionLogs.size()>0){
            for (MiniVersionLogEntity miniVersionLog : miniVersionLogs){
                if (miniVersionLog.getStatus().equals(MiniVersionStatus.PUBLISH)){
                    dto1.setData("线上版本：");
                    dto1.setText(miniVersionLog.getEdition());
                    break;
                }
            }
            for (MiniVersionLogEntity miniVersionLog : miniVersionLogs){
                if (miniVersionLog.getStatus().equals(MiniVersionStatus.AUDIT)){
                    dto2.setData("审核版本：");
                    dto2.setText(miniVersionLog.getEdition());
                    break;
                }
            }
        }
        MiniAppSimpleDTO dto3 = new MiniAppSimpleDTO();
        dto3.setData("系统版本：");
        dto3.setText(miniProduct.getEdition());

        MiniAppSimpleDTO dto4 = new MiniAppSimpleDTO();
        dto4.setData("更新状态：");
        dto4.setText(miniUserProduct.getStatus().getDesc());

        info.add(dto1);
        info.add(dto2);
        info.add(dto3);
        info.add(dto4);

        return R.ok().put("mainData",info).put("status",miniUserProduct.getStatus());
    }

    /**
     * 获取二维码图片
     */

    @GetMapping("/get_main_code")
    public void mainCodeUrl(HttpServletResponse response) throws WxErrorException {


        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        try{
            //获取图片验证码
            MiniUserProductEntity miniUserProduct = miniUserProductService.findByAppid(getAppid());
            String accessToken = wxOpenService.getWxOpenComponentService().getAuthorizerAccessToken(miniUserProduct.getWxAppid(),true);
            MiniProductEntity miniProductEntity = miniProductService.getById(miniUserProduct.getProductId());
            Getwxacode getwxacode = new Getwxacode(miniProductEntity.getHomePage(),430,true,new LineColor("0","0","0"));

            //获取图片验证码
            BufferedImage image =  WxaAPI.getwxacode(accessToken,getwxacode);

            ServletOutputStream out = response.getOutputStream();
            ImageIO.write(image, "jpg", out);
            IOUtils.closeQuietly(out);
        } catch (Exception e) {
            logger.error("qrCode", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取状态
     * @return
     */
    @GetMapping("/get_status")
    @ResponseBody
    public R getStatus(){

        MiniUserProductEntity miniUserProduct = miniUserProductService.findByAppid(getAppid());
        return R.ok().put("status", miniUserProduct.getStatus());
    }

    /**
     * 获取版本信息列表
     */


    @GetMapping("/get_version")
    @ResponseBody
    public R getVersionList(){

        MiniUserProductEntity miniUserProduct = miniUserProductService.findByAppid(getAppid());

        List<MiniVersionLogEntity> miniVersionLogs = miniVersionLogService.findByUserProductId(miniUserProduct.getId());

        return R.ok().put("versionData", miniVersionLogs);
    }
    /**
     * 获取绑定小程序体验者
     */

    @RequestMapping("/get_test")
    @ResponseBody
    public R getTest(){

        MiniUserProductEntity miniUserProduct = miniUserProductService.findByAppid(this.getAppid());
        List<MiniTesterEntity> testData = miniTesterService.findByMiniUserProductId(miniUserProduct.getId());
        return R.ok().put("testData",testData);
    }

    /**
     * 绑定小程序体验着
     */
    @GetMapping("/binding_test")
    @ResponseBody
    public R bindingTest(@RequestParam String wechatId) throws WxErrorException {

        MiniUserProductEntity miniUserProduct = miniUserProductService.findByAppid(this.getAppid());
        String accessToken ;
        try{
            accessToken = wxOpenService.getWxOpenComponentService().getAuthorizerAccessToken(miniUserProduct.getWxAppid(),true);
        }catch (WxErrorException e){
            return R.error("获取授权失败，请检查！");
        }
        BaseResponse baseResponse = MemberApi.bindTester(accessToken,wechatId);
        if (baseResponse.isSuccess()){
//            保存体验者信息
            miniTesterService.saveTester(wechatId,miniUserProduct.getId());
            return R.ok();
        }else{
            return R.error(baseResponse.getErrcode(),baseResponse.getErrmsg());
        }
    }
    /**
     * 解除绑定小程序体验着
     */
    @GetMapping("/unbinding_test")
    @ResponseBody
    public R unbindingTest(@RequestParam String wechatId) throws WxErrorException {
        MiniUserProductEntity miniUserProduct = miniUserProductService.findByAppid(this.getAppid());
        String accessToken ;
        try{
            accessToken = wxOpenService.getWxOpenComponentService().getAuthorizerAccessToken(miniUserProduct.getWxAppid(),true);
        }catch (WxErrorException e){
            return R.error("获取授权失败，请检查！");
        }
        BaseResponse baseResponse = MemberApi.unBindTester(accessToken,wechatId);
        if (baseResponse.isSuccess()){
            //删除体验者信息
            miniTesterService.deleteTester(miniUserProduct.getId(),wechatId);

            return R.ok();
        }else{
            return R.error(baseResponse.getErrcode(),baseResponse.getErrmsg());
        }
    }
    /**
     * 解除授权
     */
    @GetMapping("/unbind")
    @ResponseBody
    public R unbind() {

        MiniUserProductEntity miniUserProduct = miniUserProductService.findByAppid(this.getAppid());
        miniUserProductService.changeStatus(miniUserProduct,MiniVersionStatus.DOWN);
        return R.ok("解除绑定成功");

    }


    /**
     * 审核撤回
     */

    @RequestMapping("/undo_code_audit")
    @ResponseBody
    public R undoCodeAudit(){


        MiniUserProductEntity miniUserProduct = miniUserProductService.findByAppid(this.getAppid());
        String accessToken ;
        try{
            accessToken = wxOpenService.getWxOpenComponentService().getAuthorizerAccessToken(miniUserProduct.getWxAppid(),true);
        }catch (WxErrorException e){
            return R.error("获取授权失败，请检查！");
        }

        if (BaseUtils.isEmpty(miniUserProduct)){
            throw new RRException("访问异常");
        }
        BaseResponse baseResponse  = CodeApi.undoCodeAudit(accessToken);

        if (baseResponse.isSuccess()){
            miniUserProductService.changeStatus(miniUserProduct,MiniVersionStatus.RE_AUDIT);
            return R.ok();
        }else{
            return R.error(baseResponse.getErrcode(),baseResponse.getErrmsg());
        }
    }
    /**
     * 发布新版本
     */
    @GetMapping("/release")
    @ResponseBody
    public R release() {
        //直接发布版本

        MiniUserProductEntity miniUserProduct = miniUserProductService.findByAppid(this.getAppid());
        String accessToken ;
        try{
            accessToken = wxOpenService.getWxOpenComponentService().getAuthorizerAccessToken(miniUserProduct.getWxAppid(),true);
        }catch (WxErrorException e){
            return R.error("获取授权失败，请检查！");
        }
        if (!miniUserProduct.getStatus().equals(MiniVersionStatus.PASS)){
            logger.info("代码表示不是审核通过");
            return R.error("代码发布失败");
        }
        BaseResponse baseResponse  = CodeApi.release(accessToken);
        if (baseResponse.isSuccess()){
            miniUserProductService.changeStatus(miniUserProduct,MiniVersionStatus.PUBLISH);
            return R.ok("发布成功！");
        }

        return R.error("发布失败！"+baseResponse.getErrmsg());
    }
    /**
     * 上传代码
     */

    @GetMapping("/commit")
    @ResponseBody
    public R commit() {
       return miniUserProductService.commitByAppid(this.getAppid());

    }



    /**
     * 小程序体验码
     */
    @GetMapping("/get_qr_code")
    public void qrCode(HttpServletResponse response)throws  IOException {
        response.addHeader("Content-Disposition","attachment;filename=qrcode.jpeg");
        response.setContentType("application/octet-stream");
        //获取图片验证码
        MiniUserProductEntity miniUserProduct = miniUserProductService.findByAppid(this.getAppid());
        String accessToken = null;
        try{
            accessToken = wxOpenService.getWxOpenComponentService().getAuthorizerAccessToken(miniUserProduct.getWxAppid(),true);
        }catch (WxErrorException e){
            logger.info("获取授权失败，请检查！");
        }

        GetQrcodeResult mediaFile = WxaAPI.get_qrcode(accessToken);
        //获取图片验证码
        BufferedImage image = mediaFile.getBufferedImage();

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

}
